<template>
  <div class="setting-approve">
    <el-radio-group class="mar-b-5" v-model="approveSetting.level" @change="switchLevel">
      <el-radio :label="0">{{$t('event.setting.serviceEventTypeSetting.flow.component.approveSetting.label1')}}</el-radio>
      <el-radio :label="1">{{$t('common.base.approveLevel', {data1:$t('common.base.number1')})}}</el-radio>
      <el-radio :label="2">{{$t('common.base.approveLevel', {data1:$t('common.base.number2')})}}</el-radio>
      <template v-if="isShowVipApprove">
        <el-radio :label="4">{{$t('common.base.heightApproveLevel')}}</el-radio>
      </template>
      <slot name="reassign"></slot>
    </el-radio-group>
    <template v-if="isChooseVipApproval">
      <div class="approve-paas">
        <div class="approve-paas-title">
          <div class="title-detail">{{$t('common.zhongqi.approvalProcess')}}</div>
          <el-button type="primary" @click="editFlow">{{$t('common.zhongqi.setApprove')}}</el-button>
        </div>
        <div class="paas-preview" v-loading="loadingShow">
          <iframe v-if="reloadIframe" id="paasIframe" ref="iframePage" :src="iframeUrl" height="500px" width="100%" @load="loadingShow = false" />
        </div>
      </div>
    </template>
    <template v-else>
      <div v-if="approveSetting.level >= 1 && approveSetting.level !==3" class="setting-approve-people">
        <!--S 一级审批设置 -->
        {{$t('common.form.setting.approveSetting.des1')}}{{ approveSetting.level > 1 ? $t('common.base.approveLevelUser', {data1:$t('common.base.number1')}) : $t('common.base.approveUser') }}
        <el-tooltip :disabled="!approveSetting.leader || options.some(opt => approveSetting.leader === opt.value)" :content="$t('event.setting.serviceEventTypeSetting.flow.component.approveSetting.tips1')">
          <el-select
              class="w-187 mr-5 ml-5"
              :value="approveSetting.leader"
              :placeholder="$t('common.placeholder.select')"
              @change="(val) => updateApproveSetting('leader', val, 1)"
          >
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            >
            </el-option>
          </el-select>
        </el-tooltip>
        <template v-if="approveSetting.leader === 'users'">
          <el-input
              v-if="!isOpenData"
              class="w-187 mr-5"
              :placeholder="$t('common.placeholder.selectSomething', {0:$t('common.base.approveUser')})"
              readonly
              :value="getApproverNames(approveSetting.approvers)"
              @click.native="selectApproveUser(1)"
          />
          <div v-else class="setting-open-data-input block-inline w-187 mr-5" @click="selectApproveUser(1)">
            <template v-if="!approveSetting.approvers || !approveSetting.approvers.length"><span class="placeholder-text">{{$t('common.placeholder.selectSomething', {0:$t('common.base.approveUser')})}}</span></template>
            <template v-else v-for="(item, index) in getApproverIds(approveSetting.approvers)">
              <open-data :key="item" type="userName" :openid="item"></open-data>
              <ui-separator :index="index" :list="getApproverIds(approveSetting.approvers)" :key="`${item}${uuid()}`" />
            </template>
            <!-- <open-data v-for="staffId in getApproverIds(approveSetting.approvers)" :key="staffId" type="userName" :openid="staffId"></open-data> -->
          </div>
          <!-- <el-button class="ml-12" type="primary" size="small" @click="selectApproveUser(1)">添加审批人</el-button> -->
        </template>
        <!--E 一级审批设置 -->
        <!--S 二级以上审批设置 -->
        <template v-if="approveSetting.level > 1 && approveSetting.level !==3">
        <span
            v-for="(setting, idx) in approveSetting.multiApproverSetting"
            :key="idx"
            class="setting-approve-people"
        >
          {{$t('common.base.approveLevelUser', {data1:formatNumToCN((idx + 2))})}}
          <el-tooltip :disabled="!approveSetting.multiApproverSetting[idx].leader || options.some(opt => approveSetting.multiApproverSetting[idx].leader === opt.value)" :content="$t('event.setting.serviceEventTypeSetting.flow.component.approveSetting.tips1')">
            <el-select
                class="w-187 mr-5 ml-5"
                :value="setting.leader"
                :placeholder="$t('common.placeholder.select')"
                @change="(val) => updateApproveSetting('leader', val, idx + 2)"
            >
              <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              >
              </el-option>
            </el-select>
          </el-tooltip>
          <template v-if="setting.leader === 'users'">
            <el-input
                v-if="!isOpenData"
                class="w-187"
                :placeholder="$t('common.placeholder.selectSomething', {0:$t('common.base.approveUser')})"
                readonly
                :value="getApproverNames(setting.approvers)"
                @click.native="selectApproveUser(idx + 2)"
            />
            <div v-else-if="isOpenData" class="setting-open-data-input block-inline w-187" @click="selectApproveUser(idx + 2)">
              <template v-if="!setting.approvers || !setting.approvers.length"><span class="placeholder-text">{{$t('common.placeholder.selectSomething', {0:$t('common.base.approveUser')})}}</span></template>
              <template v-else v-for="(item, index) in getApproverIds(setting.approvers)">
                <open-data :key="item" type="userName" :openid="item"></open-data>
                <ui-separator :index="index" :list="getApproverIds(setting.approvers)" :key="`${item}${uuid()}`" />
              </template>
              <!-- <open-data v-for="staffId in getApproverIds(setting.approvers)" :key="staffId" type="userName" :openid="staffId"></open-data> -->
            </div>
          </template>
        </span>
        </template>
        <!--E 二级以上审批设置 -->
      </div>
    </template>

    <!-- 设置高级审批 -->
    <WorkflowDialog ref="workFlowDialogRef" @refreshIframe="refreshIframe"/>
  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform'
import _ from 'lodash';
/* utils*/
import { ApproverSetting } from '../models/ServiceEventConfig';
/* components*/
import WorkflowDialog from '@src/component/compomentV2/AdvancedApproval/WorkflowDialog.vue';
/* enum*/
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser'
/* 灰度*/
import { haveEventVipApproveGray } from '@src/util/grayInfo'
/* api*/
import { createVipApproveFlowForEvent } from '@src/api/EventApi'

export default {
  name: 'approve-setting',
  props: {
    options: {
      type: Array,
      default: () => [],
    },
    approveSetting: {
      type: Object,
      default: () => new ApproverSetting(),
    },
    flowType: {
      type: String,
      default: ''
    },
    taskTypeId: {
      type: String,
      default: ''
    },
  },
  components: {
    WorkflowDialog
  },
  computed: {
    // 是否开启了事件高级审批的灰度
    isShowVipApprove() {
      return haveEventVipApproveGray()
    },
    // 是否选择的高级审批
    isChooseVipApproval() {
     return this.approveSetting.level === 4;
    }
  },
  data() {
    return {
      isOpenData,
      loadingShow: false,
      reloadIframe: true,
      iframeUrl: '',
      iframeEditUrl: '', // 编辑的url
      paasIds: {
        appId: null,
        formTemplateId: null,
      },
    }
  },
  methods: {
    toShowApproveVip() {
      this.approveSetting.vipApprove = 1
      const {appId, formTemplateId} = this.approveSetting.vipApproveSetting
      this.paasIds = this.approveSetting.vipApproveSetting
      this.iframeUrl = `/paas/#/workflow?appId=${appId}&formId=${formTemplateId}&mode=preview`
      this.iframeLoad()
    },
    refreshIframe() {
      this.$refs.iframePage?.contentWindow?.location?.reload(true)
    },

    getInitData() {
      let params = {
        eventTypeId: this.taskTypeId,
        node: this.flowType,
      }

      createVipApproveFlowForEvent(params).then((res) => {
        if (res.success) {
          this.paasIds = res.result

          // 设置为高级审批
          this.approveSetting.vipApprove = 1
          this.approveSetting.vipApproveSetting = res.result
          this.iframeUrl = `/paas/#/workflow?appId=${res.result.appId}&formId=${res.result.formTemplateId}&mode=preview`
          this.iframeLoad()
        }
      })
    },

    iframeLoad() {
      this.loadingShow = true;
      const iframe = this.$refs.iframePage;
      if (iframe?.attachEvent) { // IE
        iframe.attachEvent('onload', () => { this.loadingShow = false; });
      } else { // 非IE
        iframe.onload =  () => { this.loadingShow = false; };
      }
    },

    editFlow() {
      // 不知道为啥appId没了，再次赋值
      !this.paasIds.appId ? this.paasIds = this.approveSetting.vipApproveSetting : ''
      const iframeEditUrl = `/paas/#/workflow?appId=${this.paasIds.appId}&formId=${this.paasIds.formTemplateId}&taskTypeId=${this.taskTypeId}&taskFlowType=${this.flowType}&moduleType=eventModule`
      this.$refs.workFlowDialogRef.openWorkflowHasUrl(iframeEditUrl, this.paasIds);
    },

    /** 选择审批等级 */
    switchLevel(val) {
      this.approveSetting.approvers = [];
      this.approveSetting.leader = '';
      this.approveSetting.level = val;
      this.approveSetting.multiApproverSetting = [];
      if (val > 1 && ![3, 4].includes(val)) {
        this.approveSetting.multiApproverSetting = [
          {
            leader: '',
            approvers: [],
          },
        ];
      }

      if (val === 4) {
        if (!this.iframeUrl) {
          // approveSetting有值取之前配置的审批流程
          if(this.approveSetting.vipApproveSetting?.appId && this.approveSetting.vipApproveSetting?.formTemplateId) {
            this.toShowApproveVip()
          }else {
            this.getInitData()
          }
        }
      } else {
        this.approveSetting.vipApprove = 0
    //    this.approveSetting.vipApproveSetting = {}
      }

    },
    getApproverNames(approvers) {
      return approvers.map(item => item.displayName).join(',');
    },
    getApproverIds(approvers) {
      return approvers.map(item => item.staffId);
    },
    /**
     * 更新审批设置
     *
     * @param {string} key 更新的key值
     * @param {string} value 更新值
     * @param {number} level 更新审批的层级
     */
    updateApproveSetting(key, value, level) {
      let approveSetting = _.cloneDeep(this.approveSetting);

      // 一级设置
      if (level <= 1) {
        approveSetting[key] = value;
        if (approveSetting.leader !== 'users') {
          approveSetting.approvers = [];
        }
      }
      // 多级设置
      if (level > 1) {
        let multiApproverSetting = approveSetting.multiApproverSetting[level - 2];
        multiApproverSetting[key] = value;
        if (multiApproverSetting.leader !== 'users') {
          multiApproverSetting.approvers = [];
        }
      }

      this.$emit('change', approveSetting);
    },
    /**
     * 选择指定的审批人员
     * @param {number} level 审批的层级
     */
    selectApproveUser(level) {
      let selected = level < 2
        ? this.approveSetting.approvers
        : this.approveSetting.multiApproverSetting[level - 2].approvers;
      let options = {
        title: this.$t('common.base.tip.chooseApproveUser'), // [选填] 默认值为 '请选择人员'
        max: 14, // [选填]最大人数：当值小于等于0或者不填时，不对选择人数做限制，max值为1时单选，大于1时多选
        selectedUsers: selected, // [选填] 已选人员 每个人员必须包括userId,displayName,staffId,head这四个属性，只有带max大于1时生效
        mode: BaseSelectUserModeEnum.Filter
      };

      this.$fast.select.multi.user(options)
        .then(res => {
          if (res.status != 0) return;

          this.updateApproveSetting('approvers', res.data.users, level);
        })
        .catch(err => {
          console.warn(err);
        });
    },
    formatNumToCN(num) {
      let changeNum = [
        this.$t('common.base.number0'),
        this.$t('common.base.number1'),
        this.$t('common.base.number2'),
        this.$t('common.base.number3'),
        this.$t('common.base.number4'),
        this.$t('common.base.number5'),
        this.$t('common.base.number6'),
        this.$t('common.base.number7'),
        this.$t('common.base.number8'),
        this.$t('common.base.number9'),
      ];

      return changeNum[num];
    },
  },
  watch: {
    approveSetting: {
      deep: true,
      handler(val) {
        // 先让iframe销毁
        this.reloadIframe = false;
        this.iframeUrl = null
        this.$nextTick(() => {
          if (this.approveSetting.vipApproveSetting?.appId && this.approveSetting.vipApproveSetting?.formTemplateId) {
            const {appId, formTemplateId} = this.approveSetting.vipApproveSetting
            this.paasIds = this.approveSetting.vipApproveSetting
            // 赋值地址，再加载
            this.iframeUrl = `/paas/#/workflow?appId=${appId}&formId=${formTemplateId}&taskTypeId=${this.taskTypeId}&taskFlowType=${this.flowType}&mode=preview`
          }
          this.reloadIframe = true;
        })
      }
    }
  },
  mounted() {
    // copy工单高级审批
    if(this.isShowVipApprove) {
      // 初始化level是4的话，并且是第一次初始化的话 就请求接口
      if (this.approveSetting.vipApprove) {
        this.toShowApproveVip()
      } else {
        if (this.approveSetting.level === 4 && !this.approveSetting.vipApprove) {
          this.getInitData()
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
// 企微端样式
@import '@src/modules/setting/openData.scss';

.setting-approve {
  &-people {
    line-height: 40px;
    margin-bottom: 12px;
    font-size: 14px;
    color: #999999;
  }
}
.mr-5{
  margin-right: 5px;
}
.ml-5{
  margin-left: 5px;
}

.mt-12 {
  margin-top: 12px;
}

.mb-12 {
  margin-bottom: 12px;
}

.w-187 {
  width: 187px;
}
.block-inline {
  display: inline-block;
}
.approve-paas {

  &-title {
    display: flex;
    justify-content: space-between;
    margin: 10px 0;
    line-height: 30px;
    .title-detail {
      color: #333333d1;
      font-size: 14px;
      font-weight: bolder;
    }
  }

  .paas-preview {
    border-radius: 4px;
    padding: 10px 12px;
    background: #F2F2F2;
    cursor: pointer;

    #paasIframe {
      height: 500px;
      margin: 0 auto;
    }
  }
}
</style>
